package com.github.shiqiyue.learn.guava;

import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Set;

/***
 * MultiSet 测试
 * @author wenyao.wu
 * @date 2018/7/2
 */
public class MultiSetTest {

    private static final Logger logger = LoggerFactory.getLogger(MultiSetTest.class);

    public static void main(String[] args) {
        //create a multiset collection
        /***
         * set ，可以统计相同数据的个数
         */
        HashMultiset<String> multiset = HashMultiset.create();
        multiset.add("a");
        multiset.add("b");
        multiset.add("c");
        multiset.add("d");
        multiset.add("a");
        multiset.add("b");
        multiset.add("c");
        multiset.add("b");
        multiset.add("b");
        multiset.add("b");
        //print the occurrence of an element
        logger.info("Occurrence of 'b' : {}", multiset.count("b"));
        //print the total size of the multiset
        logger.info("Total Size : {}", multiset.size());
        //get the distinct elements of the multiset as set
        Set<String> set = multiset.elementSet();
        //display the elements of the set
        logger.info("Set :{}", set);

        //display all the elements of the multiset using iterator
        Iterator<String> iterator = multiset.iterator();
        logger.info("display all the elements of the multiset using iterator,[");
        while (iterator.hasNext()) {
            logger.info(iterator.next());
        }
        logger.info("]");
        //display the distinct elements of the multiset with their occurrence count
        logger.info("display the distinct elements of the multiset with their occurrence count [");
        for (Multiset.Entry<String> entry : multiset.entrySet()) {
            logger.info("Element: " + entry.getElement() + ", Occurrence(s): " + entry.getCount());
        }
        logger.info("]");

        //remove extra occurrences
        multiset.remove("b", 2);
        //print the occurrence of an element
        logger.info("Occurence of 'b' : " + multiset.count("b"));
    }
}
